'use strict';

var Category = require('../model/category.js');
var redisCo = require('../model/redisCo.js');

/**
 * save then load to redis
 */
function* save(category) {
	var result = yield category.save();

	// yield redisCo.set('name', 'wzq');
	// console.log(yield redisCo.get('name'));

	yield saveToRedis(category);
	yield getFromRedis(result._id); // test get

	return result;
}

function* saveToRedis(cate) {
	console.log('---save to redis,id=' + cate._id);
	// hmset('key', jsonObject) 会出错,必须列举
	yield redisCo.hmset('category:' + cate._id, '_id', cate._id, 'pCode', cate.pCode, 'name', cate.name, 'desc', cate.desc);
}


function* getFromRedis(id) {
	console.log('---get from redis,id=' + id);
	var result = yield redisCo.hmget('category:' + id, ['_id', 'pCode', 'name', 'desc']);
	// result 是一个数组 
	console.log(result);
	// console.log(typeof result._id);

	if (!result[0]) {
		return null;
	}

	var cate = {
		_id: result[0],
		pCode: result[1],
		name: result[2],
		desc: result[3]
	};

	return cate;
}

/**
 * first query redis, then mongodb
 */
function* findAll() {
	var result = yield Category.find({}).exec();
	return result;
}

function* findById(id) {
	console.log("findById, id=" + id);

	// 判断是否在redis中
	var cateFromRedis = yield getFromRedis(id);
	console.log('cateFromRedis', cateFromRedis);

	if (cateFromRedis !== null) {
		console.log('find in redis');
		return cateFromRedis;
	}

	// not in redis
	console.log('not in redis');
	try {
		var result = yield Category.find({
			_id: id
		}).exec();
		yield saveToRedis(result);
		

	} catch (e) {
		return e.toString();
	}

}

function* findChildByPid(pid) {

}



module.exports.save = save;
module.exports.findAll = findAll;
module.exports.findById = findById;
module.exports.findChildByPid = findChildByPid;